from flask import current_app
from sqlalchemy import Column, String, Integer, ForeignKey, Boolean, func
from sqlalchemy.orm import relationship

from apps.spider.yushu_book import YuShuBook
from .base import db, Base


class Wish(Base):
    __tablename__ = 'wish'

    id = Column(Integer, primary_key=True)
    user = relationship('User')
    uid = Column(Integer, ForeignKey('user.id'), nullable=False)
    isbn = Column(String(13), nullable=False)
    launched = Column(Boolean, default=False)

    @property
    def book(self):
        yushu_book = YuShuBook()
        yushu_book.search_by_isbn(self.isbn)
        return yushu_book.first

    @classmethod
    def recent(cls, uid):
        recent_wishes = Wish.query.filter_by(uid=uid, launched=False).group_by(
            Wish.isbn).order_by(
            Wish.create_time.desc()).limit(
            current_app.config['RECENT_GIFT_COUNT']).distinct().all()
        return recent_wishes

    @classmethod
    def get_user_wish(cls, isbn_list):
        from apps.models.gift import Gift
        single_wish_count = db.session.query(Gift.isbn, func.count(Gift.id)
                                             ).filter(Gift.launched == False,
                                                      Gift.status == 1, Gift.isbn.in_(isbn_list)
                                                      ).group_by(Gift.isbn
                                                                 ).all()
        wish_count_list = [{'isbn': x[0], 'count': x[1]} for x in single_wish_count] if single_wish_count else []
        return wish_count_list
